<?php
namespace xcom\model;
use x\Xbase;
class AdminUser extends Xbase
{
    public function __construct(){
        parent::__construct();
    }
    /**
     * 是否登陆
     * @param  [type]  $token [登陆token]
     * @return boolean        [description]
     */
    public function isLogin(){
            $token = cookie('token');
            if($token){
                $rs = $this->db->query("select * from admin_user where token=?",[$token],1);
                return $rs ? $rs : [];
            }
            return [];
    }
    /**
     * 登录
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     */
  	public function login($username, $password){
        /* 获取用户数据 */
        $user = $this->db->query('select * from admin_user where username=?',[$username],1);
        if (empty($user) || (int)$user['status'] !== 0) {
            $this->setError('用户不存在或被禁用','username');
            return false;
        }
        if($user['password'] != com_password($password)){
            $data = [
                'id' => $user['id'],
                'error_times'=>$user['error_times']+1
            ];
            $this->db->update('admin_user',$data);
            $this->setError('密码错误','password');
            return false;
        }
        $token = token($user['id']);
        $data = [
            'id' => $user['id'],
            'token' => $token,
            'last_login_ip' => ip(),
            'last_login_time' => time(),
            'login_times' => $user['login_times']+1,
            'error_times' => 0,
        ];
        $this->db->update('admin_user',$data);
        m('Log','xcom')->record($user['id'], '登录', 'admin_user');
        cookie('token',$token);
        return $token;
  	}

    /**
     * 删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function del($id){
        if(!is_array($id)) $id = [$id];
        foreach($id as $v){
            if(!$this->checkDel($v)) return false;
            $this::destroy(function($query)use($v){
                $query->where('id',$v);
            },true);
        }
        return true;
    }
    /**
     * 验证是否可删除
     * @param unknown $id  用户id
     * @return true(可以删除) or false;
     */
    public function checkDel($id){
       $rs = $this::get($id);
       if( $rs->getData('type')==1 ){
            $this->error = '超级管理员不可删除';
            return false;
       }
       return true;
    }
}
